from cryptography.fernet import InvalidToken
from rest_framework import status
from rest_framework.views import APIView
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.views import TokenObtainPairView

from user_info.models import User
from user_info.serialzier import RegisterSerializer, LoginSerializer, UserSerializer
from utils.authentications import generate_jwt
from utils.common.base_response import APIResponse


class Register(APIView):
    def post(self, request):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            username = serializer.validated_data.get("username")
            password = serializer.validated_data.get("password")
            user = User.objects.create_user(username=username, password=password)
            return APIResponse(msg="注册成功")
        else:
            return APIResponse(msg="注册失败")


class LoginView(APIView):
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            user = serializer.validated_data.get("user")
            # ser =LoginSerializer(data=serializer.validated_data)
            ser = UserSerializer(user)
            token = generate_jwt(user)
            return APIResponse(data={"token": token,"user":ser.data})
        else:
            return APIResponse(data=serializer.errors)

class LogoutView(APIView):
    def post(self, request):
        pass
